# 快慢指针 + 栈

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        slow, fast = head, head
        stack = []
        mval = float('-inf')

         # 将前半部分入栈
        while fast and fast.next:
            stack.append(slow.val)  # 在移动前存储当前值
            slow = slow.next
            fast = fast.next.next
        
        # 处理后半部分，与栈中元素配对
        while slow:
            temp = stack.pop() + int(slow.val)
            mval = max(mval, temp)
            slow = slow.next
        
        return mval

# 快慢指针+ 反转链表
class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        slow, fast = head, head.next
        while fast.next:
            slow = slow.next
            fast = fast.next.next

        # 反转链表
        last = slow.next
        while last.next:
            cur = last.next
            last.next = cur.next
            cur.next = slow.next
            slow.next = cur

        ans = 0
        x, y = head, slow.next
        while y:
            ans = max(ans, x.val + y.val)
            x, y = x.next, y.next
        return ans